//
//  CameraViewController.m
//  JewelryStore
//
//  Created by lcs on 16/10/10.
//  Copyright © 2016年 com. All rights reserved.
//

#import "CameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UIImageView+Gestures.h"
#import "AppDelegate+Umeng.h"


#define kScreenBounds   [UIScreen mainScreen].bounds
#define kScreenWidth  kScreenBounds.size.width*1.0
#define kScreenHeight kScreenBounds.size.height*1.0
@interface CameraViewController ()

//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property(nonatomic, strong)AVCaptureDevice *device;

//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property(nonatomic, strong) AVCaptureDeviceInput *input;

//当启动摄像头开始捕获输入
@property(nonatomic, strong) AVCaptureMetadataOutput *output;

@property (nonatomic, strong) AVCaptureStillImageOutput *ImageOutPut;

//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property(nonatomic, strong) AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property(nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic, strong) UIButton *PhotoButton;
@property (nonatomic, strong) UIImageView *imageView;  //实时画面
@property (nonatomic, strong) UIImageView *imgView;   //展示外面传入的图片
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImage *resultImage;

@property (nonatomic, assign) BOOL canCa;
@property (nonatomic, assign) BOOL isTakePhoto;

@end

@implementation CameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _canCa = [self canUserCamear];
    if (_canCa) {
        _isTakePhoto = YES;
        [self customCamera];
        [self customUI];
        
    }else{
        return;
    }
}
- (void)customUI{

    _imgView = [[UIImageView alloc] initWithImage:_ringImage andFrame:self.view.frame addSuperView:self.view];

    _PhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_PhotoButton setImage:[UIImage imageNamed:@"photo"] forState: UIControlStateNormal];
    [_PhotoButton addTarget:self action:@selector(shutterCamera) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_PhotoButton];
    
    [_PhotoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(@-20);
        make.width.equalTo(@60);
        make.height.equalTo(@60);
    }];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setTitle:@"取消" forState:UIControlStateNormal];
    leftButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [leftButton addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_PhotoButton);
        make.left.equalTo(@50);
        make.width.equalTo(@60);
        make.height.equalTo(@60);
    }];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"分享" forState:UIControlStateNormal];
    rightButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [rightButton addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightButton];
    
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_PhotoButton);
        make.right.equalTo(@-50);
        make.width.equalTo(@60);
        make.height.equalTo(@60);
    }];
    
}
- (void)customCamera{
    self.view.backgroundColor = kWhite;
    
    //使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //使用设备初始化输入
    self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    
    //生成输出对象
    self.output = [[AVCaptureMetadataOutput alloc]init];
    self.ImageOutPut = [[AVCaptureStillImageOutput alloc] init];
    
    //生成会话，用来结合输入输出
    self.session = [[AVCaptureSession alloc]init];
    if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
        
        self.session.sessionPreset = AVCaptureSessionPreset1280x720;
        
    }
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
    }
    
    //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    
    //开始启动
    [self.session startRunning];
    if ([_device lockForConfiguration:nil]) {
        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [_device setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_device unlockForConfiguration];
    }
}

#pragma mark - 截取照片
- (void)shutterCamera
{
    AVCaptureConnection * videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection) {
        NSLog(@"take photo failed!");
        return;
    }
    
    if (_isTakePhoto) {
        [self takePhotoWithConnection:videoConnection];
        _isTakePhoto = NO;
    }else
    {
        _resultImage = [self composeImgWithBackgroundImag:_imageView.image andOtherImg:_imgView];
        [self saveImageToPhotoAlbum:_resultImage];
    }

}

- (void)takePhotoWithConnection:(AVCaptureConnection *)videoConnection
{
    [self.ImageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        self.image = [UIImage imageWithData:imageData];
        [self.session stopRunning];
        self.imageView = [[UIImageView alloc]initWithFrame:self.previewLayer.frame];
        [self.view insertSubview:_imageView belowSubview:_PhotoButton];
        self.imageView.layer.masksToBounds = YES;
        self.imageView.image = _image;
        [self.view insertSubview:_imgView aboveSubview:_imageView];
        NSLog(@"image size = %@",NSStringFromCGSize(self.image.size));
    }];

}
#pragma - 保存至相册
- (void)saveImageToPhotoAlbum:(UIImage*)savedImage
{
    
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    
}
// 指定回调方法

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo

{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}
-(void)cancle{
    
    if (self.imageView.superview) {
        [self.imageView removeFromSuperview];
        [self.session startRunning];
        _isTakePhoto = YES;;
    }else
    {
        [self.session stopRunning];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
#pragma mark - 检查相机权限
- (BOOL)canUserCamear{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alertView.tag = 100;
        [alertView show];
        return NO;
    }
    else{
        return YES;
    }
    return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0 && alertView.tag == 100) {
        
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }
}

//合并两张图
- (UIImage *)composeImgWithBackgroundImag:(UIImage *)backgroundImg andOtherImg:(UIImageView *)imgView {
 
    //为画布创建上下文
    UIGraphicsBeginImageContext(CGSizeMake(kScreenWidth, kScreenHeight));
    [backgroundImg drawInRect:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];//先把1.png 画到上下文中
    [imgView.image drawInRect:_imgView.frame];//再把小图放在上下文中
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();//从当前上下文中获得最终图片
    UIGraphicsEndImageContext();//关闭上下文
    
    return resultImg;
}

#pragma mark - 分享
- (void)share
{
    //上传图片给服务器
    _resultImage = [self composeImgWithBackgroundImag:_imageView.image andOtherImg:_imgView];

    //取出返回数据中的链接
    
    //分享链接
    ShareInfo *info = [[ShareInfo alloc] initWithTitle:@"💍试戴" content:@"李财神珠宝商城戒指试戴" thumbImage:_resultImage webPageUrl:@"www.baidu.com"];
    [AppDelegate showUmengShareMenuViewWithShareinfo:info];

}
@end
